package com.cn.xcsharp.util;

import com.cn.xcsharp.bean.PagingBean;
import org.springframework.dao.DataAccessException;
import org.springframework.jdbc.core.JdbcTemplate;

import java.util.ArrayList;
import java.util.List;
import java.util.Map;

/**
 * 分页工具
 */
public class PagingUtils {
    /**
     * @param sql      要执行的sql
     * @param pageNo   当前页码
     * @param pageSize 页面数据条数
     * @param template 要调用的JdbcTemplate对象
     * @param params   sql中的预处理参数
     * @return
     */
    public static PagingBean getJdbcPage(String sql, int pageNo, int pageSize, JdbcTemplate template, Object... params) {
        // 要返回的分页实体对象
        PagingBean page = new PagingBean();
        int pageNotemp = pageNo == 0 ? 1 : pageNo;
        long totalCount = 0;
        long startIndex = 0;
        long endIndex = 0;

        String countSql = "select count(*) from ("+ sql+ ")";
        try {
            totalCount = template.queryForObject(countSql, Long.class, params);
        } catch (DataAccessException e) {
            e.printStackTrace();
        }
        // 计算总页数
        long pageTotal = totalCount % pageSize == 0 ? totalCount / pageSize : totalCount / pageSize + 1;
        // 总记录数
        page.setTotalCount(totalCount);
        // 总页数
        page.setPageTotal(pageTotal);
        page.setPageNo(pageNotemp);
        page.setPageSize(pageSize);

        if (totalCount <= 0) {
            page.setData(new ArrayList<>());
        } else {
            // 每页起始位置
            startIndex = (pageNotemp - 1) * pageSize;
            // 每页结束为止
            endIndex = pageNotemp * pageSize;
            String pageSql = "select * from (select t1.*,rownum rn from ("+ sql+ ") t1 where rownum <="+ endIndex+ ") where rn >"+ startIndex;
            List<Map<String, Object>> list = null;
            try {
                list = template.queryForList(pageSql, params);
            } catch (DataAccessException e) {
                e.printStackTrace();
                list = new ArrayList<>();
            }
            page.setData(list);
        }
        return page;
    }
}
